#include "thread_pool.h"
#include "thread.h"
#include "../ftptask/task_base.h"
#include <thread>
#include <iostream>

#include "../util/common_util.h"

/*
 * @ hsby 分配任务到线程池
 */
void ThreadPool::Dispatch(TaskBase *task) {
	LOGDEBUG("main Thread At XThreadPoll::dispathch()");
	
	if (!task) return;
	int tid = (lastThread + 1) % threadCount;
	lastThread = tid;
	Thread* t = threads[tid];
	
	// 添加任务
	t->AddTack(task);
	// 激活线程
	t->Activate();
}

/*
 * @ hsby 初始化线程池
 */
void ThreadPool::Init(int threadCount) {
	LOGDEBUG("main Thread At XThreadPoll::Init()");
	this->threadCount = threadCount;
	this->lastThread = -1;
	for (int i = 0; i < threadCount; i++) {
		Thread *t = new Thread();
		t->id = i;
		t->Start();
		threads.push_back(t);
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}

}
